import React, { useState } from 'react';
import { Form, Input, Button, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import api from '../utils/api';

const Login = ({ onLogin }) => {
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (values) => {
    const { username, password } = values;
    
    setLoading(true);
    
    try {
      const response = await api.login(username, password);
      const { access_token, username: user } = response.data;
      
      // 保存token到本地存储
      localStorage.setItem('token', access_token);
      
      // 调用登录回调，更新应用状态
      onLogin({ username: user });
      
      message.success('登录成功');
    } catch (error) {
      console.error('登录失败:', error);
      let errorMsg = '登录失败';
      
      if (error.response && error.response.data) {
        errorMsg = error.response.data.message || errorMsg;
      }
      
      message.error(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-background">
      <div className="login-container">
        <h1 className="login-title">华泰智能诊断系统</h1>
        
        <Form
          name="login"
          initialValues={{ username: 'admin', password: 'admin' }}
          onFinish={handleSubmit}
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input 
              prefix={<UserOutlined />} 
              placeholder="用户名" 
              size="large" 
              autoComplete="username"
            />
          </Form.Item>
          
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password 
              prefix={<LockOutlined />} 
              placeholder="密码" 
              size="large"
              autoComplete="current-password"
            />
          </Form.Item>
          
          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={loading}
              size="large"
              block
            >
              登录
            </Button>
          </Form.Item>
          
          <div style={{ textAlign: 'right' }}>
            <a href="#forgot">忘记密码?</a>
          </div>
        </Form>
      </div>
    </div>
  );
};

export default Login; 